import urls from '/util/urls'
import request from '/util/request'
import moment from 'moment'
import { parseTime, isWorkerRole, weekBegin, weekEnd, alert} from '/util/utils'
const app = getApp()

Page({
  data: {
      /** 单位名称 */
    companyName: '',
    /** 单位编码 */
    companyCode: '',
    /** 创建人员 */
    userName: '',
    /** 创建人员编码 */
    userCode: '',
    /** 服务项目 */
    serviceItem: '',
    /** 服务开始时间 */
    serviceStartTime: null,
    /** 实际到场人数 */
    actualAttendanceNumber: 1,
    /** 本周工作情况 */
    weekWorkInfo: '',
    /** 下周工作计划 */
    nextWeekWorkPlan: '',
    /** 总结描述 */
    summaryDesc: '',
    /** 问题记录及解决方案 */
    problemOrSolution: '',
    /** 备注 */
    remark: '',
    /** 周次 */
    weekDate: null,
    /** 周时间 */
    weekTime: new Date(),
    /** 报告人集合 */
    availableUsers: []
  },
  onLoad() {
   request.login(this.init.bind(this))
  },
  init() {
    const that = this
    that.setData({
      companyCode: app.globalData.instituteInfo.defaultInstituteCode,
      companyName: app.globalData.instituteInfo.defaultInstituteName,
      weekTime: new Date(),
      userName: app.globalData.userInfo.name,
      userCode: app.globalData.userInfo.username
    })
    that.getDayWorkList(app.globalData.instituteInfo.defaultInstituteCode)
    // const defaultInstitute = app.globalData.instituteInfo.institutions.find(item => item.code === app.globalData.instituteInfo.defaultInstituteCode)
    // if(defaultInstitute) {
    //   // 报告人
    //   that.setData({
    //     companyName: defaultInstitute.name
    //   })
    // }
   
    // 项目名称
    request.get(urls.projectUrl(), function(data){
      if(data){
        that.setData({
          serviceItem: data.name,
          serviceStartTime:data.startTime,
          weekDate:that.computeWeek(new Date(),data.startTime)
        });
      }
    })
  },
  onItemInput(e) {
    this.setData({
      [e.target.dataset.field]: e.detail.value,
    });
  },
  onClear(e) {
    this.setData({
      [e.target.dataset.field]: '',
    });
  },
  // 单位的弹窗
  onUnitCodePickerTap() {
    // 一线工程师只能填写自己单位下面的日报
    if(isWorkerRole() === true){
      return ;
    }
    let that = this
    const items = app.globalData.instituteInfo.institutions.map(item => item.name)
    my.showActionSheet({
      title: '选择单位',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = app.globalData.instituteInfo.institutions[res.index]
        if(i) {
          that.getDayWorkList(i.code)
          // 刷新报告人列表
          const institute = app.globalData.instituteInfo.institutions.find(item => item.code === i.code)
          this.setData({
            companyCode: i.code,
            companyName: i.name,
            userCode:'',
            userName:'',
            availableUsers:  [...institute.users,...institute.residents]
          });
        }
      },
    });
  },
  // 周次时间选择回调
  onWeekDateFocus() {
    const that = this
    dd.datePicker({
      success: (res) => {
        that.setData({
          weekTime: new Date(res.date),
          weekDate: that.computeWeek(new Date(res.date),that.data.serviceStartTime)
        });
        that.getDayWorkList(that.data.companyCode)
      },
    })
  },
  // 计算距服务开始月是第几周
  computeWeek(time,sTime){
    return parseTime(time, '{y}年') +Math.ceil(moment(time).diff(moment(sTime),'days')/7) + '周'
  },
  // 获取日报信息
  getDayWorkList(unitCode) {
    const that = this
    // 清空本周工作情况
    that.setData({
      weekWorkInfo: ''
    });

    const start = weekBegin(that.data.weekTime)
    const end  = weekEnd(that.data.weekTime)
    // 重新查询本周工作情况
    request.get(urls.dayWorkList(start,end,unitCode), function(data){
      let info = ''
      data.forEach(item => {
        info += '日期:' + parseTime(item.dailyReportDate, '{y}-{m}-{d}') + ' ' + parseTime(item.serviceStartTime, '{h}:{i}') + '至' + parseTime(item.serviceEndTime, '{h}:{i}') + '  工作内容：' + item.jobContent + '\n'
      })
      that.setData({
        weekWorkInfo: info
      })
    })

  },
  // 报告人弹窗
  onReportUserTap(){
    // 一线工程师只能填写自己单位下面的日报
    if(isWorkerRole() === true){
      return ;
    }
    let that = this
    const items = that.data.availableUsers.map(e=>e.name)

    my.showActionSheet({
      title: '选择报告人',
      items: items,
      cancelButtonText: '取消',
      success: (res) => {
        const i = that.data.availableUsers[res.index]
        if(i) {
          that.setData({
            userCode: i.username,
            userName: i.name,
          });
        }
      },
    });
  },
  // 表单校验
  validData(formData) {

    if(!formData.companyCode) {
      alert('请选择单位')
      return false
    }
    if(!formData.weekDate) {
      alert('请选择周次')
      return false
    }

    if(!formData.userCode) {
      alert('请选择报告人')
      return false
    }

     if(!formData.serviceItem) {
      alert('请选择服务项目')
      return false
    }
    return true
  },
  onSubmit() {
    const that = this
    const {
      companyName,
      companyCode,
      userName,
      userCode,
      serviceItem,
      actualAttendanceNumber,
      weekWorkInfo,
      nextWeekWorkPlan,
      summaryDesc,
      problemOrSolution,
      remark,
      weekTime
    } = this.data

    const formData = {
      companyName,
      companyCode,
      userName,
      userCode,
      serviceItem,
      actualAttendanceNumber,
      weekWorkInfo,
      nextWeekWorkPlan,
      summaryDesc,
      problemOrSolution,
      remark,
      weekDate:new Date(weekTime).getTime()
    }
   
    if(!that.validData(formData)) {
      return
    }

    dd.showLoading({
      content: '提交中...',
    })
    request.post(urls.operationSupportWeeklyUrl(), formData, () => {
      dd.hideLoading()
      //dd.alert({content: '提交成功'})
      dd.showToast({
        type: 'success',
        content: '提交成功',
        duration: 2000,
        success: () => {
          dd.redirectTo({
            url: '/pages/index/index'
          })
        },
      })
    }, () => {
      dd.hideLoading()
      dd.showToast({
        type: 'fail',
        content: '每个厅局一周只能提交一次周报',
        duration: 2000,
      })
    })
  }
});
